<template>
<div class="machine-detail full-height part none-p">
  <q-tabs
    @click="onConnect"
    v-model="tab"
    shrink stretch dense
    inline-label
    align="left"
    active-color="primary"
    indicator-color="primary"
    style="padding-left: 17px;
           position: relative"
  >
    <q-tab name="detail" label="详情" icon="iconfont icontubiao-113"
           v-stat="{id:CommonConfig.statData.machine.detail.id,name:CommonConfig.statData.machine.detail.name}"/>
    <q-tab name="process" label="实时加工" icon="iconfont icontubiao-112"
           v-stat="{id:CommonConfig.statData.machine.process.id,name:CommonConfig.statData.machine.process.id}"/>
    <q-tab name="timeline" label="时间线" icon="iconfont icontubiao-112"
           v-stat="{id:CommonConfig.statData.machine.timeline.id,name:CommonConfig.statData.machine.timeline.id}"/>
    <div class="right" style="position: absolute;right: 20px">
      <span> 所选设备：{{ this.msg.name && this.msg.assetNumber ? `${this.msg.name}(${this.msg.assetNumber})` : '--' }}</span>
      <span style="margin-left: 20px"> 网关：{{ this.msg.boxId ? this.msg.boxId : '--' }}</span>
    </div>
  </q-tabs>

  <q-separator class="line"/>
  <q-tab-panels v-model="tab" keep-alive animated class="height-full">
    <q-tab-panel name="detail" style="padding-left:0;padding-right: 0" class="full-height">
      <machine-detail-tab ref="detail"
        class="full-height"
        :msg="detailsMessage"
        :details="details"
      />
    </q-tab-panel>
    <q-tab-panel name="process" style="padding-left:0;padding-right: 0" class="full-height">
      <online-process-tab
        class="full-height"
        ref="onlineProcessTab"
        :msg="processMessage"
        :system="systemInfo"
      />
    </q-tab-panel>
    <q-tab-panel name="timeline" style="padding-left:0;padding-right: 0" class="full-height">
      <timeline ref="timeline" class="full-height" :msg="timeLineMessage" :details="details"></Timeline>
    </q-tab-panel>
  </q-tab-panels>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import MachineDetailTab from './machine-detail-tab'
import OnlineProcessTab from './online-process-tab'
import Timeline from './timeline'
import refreshMixin from '../../assets/js/refresh-mixin'

export default {
  name: 'machine-detail',
  mixins: [refreshMixin],
  data () {
    return {
      tab: 'detail', // detail / process / timeline
      details: '', // 传给子组件机床详情的数据，用于填充显示项
      systemInfo: null, // 传给子组件实时加工的数据，系统信息用于解析协议
      // timer: null, // mq定时器,60秒
      client: null, // mq实例
      detailsMessage: '', // 详情msg
      processMessage: '', // 实时加工msg
      timeLineMessage: '', // 时间线msg
      boxId: '', // 盒子Id
      params: null, // 路由携带的参数,
      // 机台状态信息
      msg: {
        name: '',
        assetNumber: '',
        boxId: ''
      }
    }
  },
  components: {
    MachineDetailTab,
    OnlineProcessTab,
    Timeline
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  watch: {
    '$route.query': {
      handler (val) {
        this.msg = Object.assign({}, this.msg, JSON.parse(val.params))
        this.initParams()
      },
      deep: true,
      immediate: true
    },
    tab (newVal) {
      this.refreshInfo()
    }
  },
  created () {
    this.params = null
    this.initParams()
    console.log('机台详情')
    // console.log(this.params, 'oooooooooooooooooo')
    this.initMqtt()
    // this.refreshInfo()
  },
  beforeDestroy () {
    // 清除定时器
    // clearInterval(this.timer)
    // 取消订阅
    this.closeUbscribeTopic()
    // 关闭连接
    this.client.disconnect()
  },

  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      // 清除定时器
      // clearInterval(this.timer)
      // 取消订阅
      // this.closeUbscribeTopic()
      // 关闭连接
      // this.client.disconnect()
      this.initParams()
      // this.initMqtt()
      switch (this.tab) {
        case 'detail':
          this.$refs.detail.init()
          break
        case 'process':
          // this.$refs.onlineProcessTab
          break
        case 'timeline':
          this.$refs.timeline.getStartDateTime()
          break
      }
    },
    // 初始化路由参数
    initParams () {
      this.details = ''
      this.details = this.$route.query.params
      this.params = JSON.parse(this.$route.query.params)
      this.boxId = this.params.boxId
      this.systemInfo = this.params.deviceInfo

      // console.log(this.params, 'system info old1111111')
    },

    // 初始化mqtt
    initMqtt () {
      console.log('机台详情mqtt连接')
      // 生成一个唯一的userId用于连接盒子，此id必须唯一
      const userId = 'webClient' + this.userInfo.user_id.toString() + Date.parse(new Date()).toString()
      // 创建mq实例
      this.client = new window.Paho.MQTT.Client(
        this.CommonConfig.mqttConfig.MQTT_SERVICE,
        Number(this.CommonConfig.mqttConfig.MQRR_PORT),
        userId)
      // 连接服务器并注册连接成功处理事件
      this.client.connect({ onSuccess: this.onConnect })
      // 注册连接断开处理事件
      this.client.onConnectionLost = this.onConnectionLost
      // 注册消息接收处理事件
      this.client.onMessageArrived = this.onMessageArrived
      // this.timer = setInterval(this.onConnect, 60000)
    },

    // 订阅并发送消息
    onConnect () {
      this.closeUbscribeTopic()
      switch (this.tab) {
        case 'detail' :
          this.client.subscribe(
            `${this.CommonConfig.mqttConfig.MQTT_TOPIC.statusTopic.subscribeTopic}${this.boxId}`, { qos: 1 }
          )// 订阅状态主题
          this.client.subscribe(
            `${this.CommonConfig.mqttConfig.MQTT_TOPIC.productivityTopic.subscribeTopic}${this.boxId}`, { qos: 1 }
          )// 订阅实际产量主题
          break
        case 'process':
          this.client.subscribe(
            `${this.CommonConfig.mqttConfig.MQTT_TOPIC.processTopic.subscribeTopic}${this.boxId}`, { qos: 1 }
          )// 订阅主题
          this.onSend(
            this.CommonConfig.mqttConfig.MQTT_TOPIC.processTopic.sendTopic,
            this.boxId,
            this.CommonConfig.mqttConfig.MQTT_TOPIC.processTopic.type
          )
          break
        case 'timeline':
          this.client.subscribe(
            `${this.CommonConfig.mqttConfig.MQTT_TOPIC.timeLineTopic.subscribeTopic}${this.boxId}`, { qos: 1 }
          )// 订阅主题
          this.onSend(
            this.CommonConfig.mqttConfig.MQTT_TOPIC.timeLineTopic.sendTopic,
            this.boxId,
            this.CommonConfig.mqttConfig.MQTT_TOPIC.timeLineTopic.type
          )
      }
    },

    // 发送消息
    onSend (sendTopic, boxId, type) {
      let message = new window.Paho.MQTT.Message(type)
      const topic = `${sendTopic}${boxId}`.toString()
      message.destinationName = topic
      this.client.send(message)
    },

    // 接受盒子返回消息
    onMessageArrived (message) {
      switch (this.tab) {
        case 'detail': this.detailsMessage = message
          break
        case 'process' : this.processMessage = message.payloadString
          break
        case 'timeline' :
          this.timeLineMessage = message.payloadString
      }
    },

    // 连接丢失
    onConnectionLost (responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log('onConnectionLost:' + responseObject.errorMessage)
        console.log('连接已断开')
      }
      this.client.connect({ onSuccess: this.onConnect })
    },

    // 取消订阅
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.statusTopic.subscribeTopic}${this.boxId}`)
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.productivityTopic.subscribeTopic}${this.boxId}`)
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.processTopic.subscribeTopic}${this.boxId}`)
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.timeLineTopic.subscribeTopic}${this.boxId}`)
    }
  }
}
</script>

<style scoped lang="stylus">
  .machine-detail{
    padding: 15px 20px;
  }
  .machine-detail.none-p{
    padding: 15px 0;
  }
  .height-full{
    height: calc(100% - 36px);
  }
</style>
